<template>
	<el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :close-on-press-escape="false"
	 :show-close="false" :visible.sync="visible" :fullscreen="true">
		<el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="100px">
			<el-tabs v-model="activeName">
				<el-tab-pane label="通用信息" name="first">
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="商品类型" prop="categoryId">
								<el-cascader placeholder="点击选择商品类型" :options="categoryTree" :props="categoryTreeProps" v-model="dataForm.categoryId"
								 change-on-select clearable style="width:100%;"></el-cascader>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="品牌" prop="brandId">
								<el-select clearable v-model="dataForm.brandId" placeholder="请选择品牌" style="width: 100%;">
									<el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="名称" prop="name">
								<el-input v-model="dataForm.name" placeholder="请输入商品名称" maxlength="30" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="商品序列号" prop="goodsSn">
								<el-input v-model="dataForm.goodsSn" placeholder="请输入商品序列号" maxlength="30" type="number"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="商品库存" prop="goodsNumber">
								<el-input-number v-model="dataForm.goodsNumber" controls-position="right" :min="0" label="商品库存" type="number"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="零售价格" prop="retailPrice">
								<el-input-number v-model="dataForm.retailPrice" controls-position="right" :min="0" label="零售价格" type="number"></el-input-number>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="市场价" prop="marketPrice">
								<el-input-number v-model="dataForm.marketPrice" controls-position="right" :min="0" label="市场价" type="number"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="排序" prop="sortOrder">
								<el-input-number v-model="dataForm.sortOrder" controls-position="right" :min="0" label="排序" type="number"></el-input-number>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="上架" prop="isOnSale">
								<el-radio-group v-model="dataForm.isOnSale">
									<el-radio :label="1">是</el-radio>
									<el-radio :label="0">否</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="新品" prop="isNew">
								<el-radio-group v-model="dataForm.isNew">
									<el-radio :label="1">是</el-radio>
									<el-radio :label="0">否</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
					</el-row>
					<el-form-item label="热销" prop="isHot">
						<el-radio-group v-model="dataForm.isHot">
							<el-radio :label="1">是</el-radio>
							<el-radio :label="0">否</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-row>
						<el-col :span="12">
							<el-form-item label="商品主图" prop="primaryPicUrl">
								<el-upload class="avatar-uploader" :action="updateUrl" :show-file-list="false" :on-success="handlePrimaryPicUrlSuccess"
								 :before-upload="beforePicUpload">
									<div v-if="dataForm.primaryPicUrl" @click.stop="handleView()">
										<img :src="dataForm.primaryPicUrl" class="pic-url" />
										<div class="upload-list-cover">
											<i class="el-icon-view" @click.stop="handleView(dataForm.primaryPicUrl)"></i>
											<i class="el-icon-delete" @click.stop="deleteBtn('primaryPicUrl')"></i>
										</div>
									</div>
									<i v-else class="el-icon-plus avatar-uploader-icon"></i>
								</el-upload>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="商品列表图" prop="listPicUrl">
								<el-upload class="avatar-uploader" :action="updateUrl" :show-file-list="false" :on-success="handleListPicUrlSuccess"
								 :before-upload="beforePicUpload">
									<div v-if="dataForm.listPicUrl" class="upload-image-cover" @click.stop="handleView()">
										<img :src="dataForm.listPicUrl" class="pic-url" />
										<div class="upload-list-cover">
											<i class="el-icon-view" @click.stop="handleView(dataForm.listPicUrl)"></i>
											<i class="el-icon-delete" @click.stop="deleteBtn('listPicUrl')"></i>
										</div>
									</div>
									<i v-else class="el-icon-plus avatar-uploader-icon"></i>
								</el-upload>
							</el-form-item>
						</el-col>
					</el-row>
				</el-tab-pane>
				<el-tab-pane label="描述信息" name="second">
					<el-form-item label="推广描述" prop="promotionDesc">
						<el-input v-model="dataForm.promotionDesc" placeholder="请输入推广描述" maxlength="30" clearable></el-input>
					</el-form-item>
					<el-form-item label="关键字" prop="keywords">
						<el-input v-model="dataForm.keywords" placeholder="请输入关键字" maxlength="30" clearable></el-input>
					</el-form-item>
					<el-form-item label="简明介绍" prop="goodsBrief">
						<el-input v-model="dataForm.goodsBrief" placeholder="请输入简明介绍" maxlength="30" clearable></el-input>
					</el-form-item>
					<el-form-item label="属性类别" prop="attributeCategory">
						<el-select clearable v-model="dataForm.attributeCategory" placeholder="请选择属性类别" @change="selectAttributeCategory"
						 style="width: 100%;">
							<el-option v-for="item in attributeCategoryList" :key="item.id" :label="item.name" :value="item.id">
							</el-option>
						</el-select>
					</el-form-item>
					<el-row :gutter="20" v-if="dataForm.attributeCategory">
						<el-col :span="12" v-for="(value,index) in attributes" :key="index">
							<el-form-item :label="value.name">
								<el-input v-model="dataForm.attributeEntityList[value.id].value" placeholder="请输入属性值" maxlength="30" clearable></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</el-tab-pane>
				<el-tab-pane label="详细描述" name="third">
					<div class="zzh-img-row">
						<el-upload :action="updateUrl" list-type="picture-card" :multiple="true" :on-preview="handlePictureCardPreview"
						 :file-list="fileList" :on-remove="handleRemove" :limit="6" :on-success="handleCarouselPicSuccess" :before-upload="beforePicUpload">
							<i class="el-icon-plus"></i>
						</el-upload>
					</div>
					<tinymce-editor id="goodsDesc" :url="updateUrl" ref="tinymce" :uploadImg="uploadImg" :value="dataForm.goodsDesc"
					 @input="getContent"></tinymce-editor>
				</el-tab-pane>
			</el-tabs>
		</el-form>
		<span slot="footer" class="dialog-footer">
			<el-button @click="cancel()">取消</el-button>
			<el-button type="primary" @click="dataFormSubmit()">确定</el-button>
		</span>
	</el-dialog>
</template>

<script>
	import {
		treeDataTranslate,
		getTreeId
	} from '@/utils'
	import TinymceEditor from '@/components/tinymce-editor'
	import PhotoViewer from 'photoviewer';
	export default {
		data() {
			return {
				// 对话框是否显示
				visible: false,
				// tab标签默认显示的标签页
				activeName: 'first',
				dataForm: {
					id: 0,
					categoryId: [],
					goodsSn: '',
					name: '',
					brandId: '',
					attributeCategory: '',
					goodsNumber: '',
					retailPrice: '',
					marketPrice: '',
					listPicUrl: '',
					primaryPicUrl: '',
					sortOrder: '',
					isOnSale: 0,
					isNew: 0,
					isHot: 0,
					promotionDesc: '',
					keywords: '',
					goodsBrief: '',
					goodsDesc: '',
					goodsImgList: [],
					attributeEntityList: {}
				},
				dataRule: {
					categoryId: [{
						required: true,
						message: '商品类型不能为空',
						trigger: 'blur'
					}],
					name: [{
						required: true,
						message: '名称不能为空',
						trigger: 'blur'
					}],
					goodsNumber: [{
						required: true,
						message: '商品库存不能为空',
						trigger: 'blur'
					}],
					retailPrice: [{
						required: true,
						message: '零售价格不能为空',
						trigger: 'blur'
					}],
					marketPrice: [{
						required: true,
						message: '市场价格不能为空',
						trigger: 'blur'
					}],
					listPicUrl: [{
						required: true,
						message: '列表图不能为空',
						trigger: 'blur'
					}],
					primaryPicUrl: [{
						required: true,
						message: '商品主图不能为空',
						trigger: 'blur'
					}]
				},
				// 品牌list
				brandList: [],
				// 属性类别
				attributeCategoryList: [],
				// 商品类型数据
				categoryList: [],
				// 商品类型树形数据
				categoryTree: [],
				// 联级选择加载项
				categoryTreeProps: {
					value: 'id',
					label: 'name',
					children: 'children'
				},
				// 图片上传路径
				updateUrl: '',
				// 富文本编辑中的图片路径
				uploadImg: [],
				// 旧图片
				oldImg: [],
				// 新图片
				newImg: [],
				// 商品属性
				attributes: [],
				// 商品轮播图上传列表
				fileList: [],
				// 商品轮播图旧图片
				oldgoodsImgList: [],
				// 修改时是否新增图片
				notNewGoodsImg: true,
				// 商品详情中的图片
				goodsDescImgList: [],
				// 商品属性、修改时有用
				goodsAttribute: []
			}
		},
		components: {
			TinymceEditor
		},
		computed: {},
		methods: {
			// 同步得到富文本的值
			getContent(content) {
				this.dataForm.goodsDesc = content
			},
			// 初始化
			init(id) {
				var that = this
				this.updateUrl = this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`)
				this.dataForm.id = id || 0
				this.$http({
					url: this.$http.adornUrl('/back/category/list'),
					method: 'get',
					params: this.$http.adornParams()
				}).then(({
					data
				}) => {
					this.categoryList = data.data
					this.categoryTree = treeDataTranslate(data.data, 'id')
				}).then(() => {
					this.visible = true
					this.uploadImg = []
					if (this.$refs.tinymce) {
						this.$refs.tinymce.setContent('')
					}
					this.$nextTick(() => {
						this.$refs['dataForm'].resetFields()
					})
				}).then(() => {
					this.getBrands()
					this.getAttributeCategories()
					if (this.dataForm.id) {
						this.$http({
							url: this.$http.adornUrl(`/back/goods/info/${this.dataForm.id}`),
							method: 'get',
							params: this.$http.adornParams()
						}).then(({
							data
						}) => {
							if (data && data.code === 0) {
								this.dataForm.categoryId = getTreeId(this.categoryList, data.data.categoryId, 'id')
								this.dataForm.goodsSn = data.data.goodsSn
								this.dataForm.name = data.data.name
								this.dataForm.brandId = data.data.brandId ? data.data.brandId : ''
								this.dataForm.attributeCategory = data.data.attributeCategory ? data.data.attributeCategory : ''
								this.dataForm.goodsNumber = data.data.goodsNumber
								this.dataForm.retailPrice = data.data.retailPrice
								this.dataForm.marketPrice = data.data.marketPrice
								this.dataForm.listPicUrl = data.data.listPicUrl
								this.dataForm.primaryPicUrl = data.data.primaryPicUrl
								this.dataForm.sortOrder = data.data.sortOrder
								this.dataForm.isOnSale = data.data.isOnSale
								this.dataForm.isNew = data.data.isNew
								this.dataForm.isHot = data.data.isHot
								this.dataForm.promotionDesc = data.data.promotionDesc
								this.dataForm.keywords = data.data.keywords
								this.dataForm.goodsBrief = data.data.goodsBrief
								this.dataForm.goodsDesc = data.data.goodsDesc ? data.data.goodsDesc : ''
								this.matchSrc(data.data.goodsDesc)
								this.oldgoodsImgList = data.data.goodsImgList
								data.data.goodsImgList.forEach(function(value, i) {
									if (value.imgUrl) {
										var goodsImg = {
											name: i,
											url: value.imgUrl,
											response: {
												url: value.imgUrl
											}
										}
										that.fileList.push(goodsImg)
									}
								})
								this.goodsAttribute = data.data.attributeEntityList ? data.data.attributeEntityList : []
								this.selectAttributeCategory(data.data.attributeCategory)
								if (this.$refs.tinymce && data.data.goodsDesc) {
									this.$refs.tinymce.setContent(data.data.goodsDesc)
								}
							}
						})
					}
				})
			},
			// 获取品牌信息
			getBrands() {
				this.$http({
					url: this.$http.adornUrl(`/back/brand/queryAll`),
					method: 'get',
					params: this.$http.adornParams()
				}).then(({
					data
				}) => {
					if (data && data.code === 0) {
						this.brandList = data.data
					} else {
						this.brandList = []
					}
				})
			},
			// 获取属性类别信息
			getAttributeCategories() {
				this.$http({
					url: this.$http.adornUrl(`/back/attributecategory/list`),
					method: 'get',
					params: this.$http.adornParams()
				}).then(({
					data
				}) => {
					if (data && data.code === 0) {
						this.attributeCategoryList = data.data.list
					} else {
						this.attributeCategoryList = []
					}
				})
			},
			// 表单提交
			dataFormSubmit() {
				for (let key in this.dataForm.attributeEntityList) {
					if (this.dataForm.attributeEntityList[key].value.replace(/(^\s*)|(\s*$)/g, "") == "") {
						this.$message.error("属性值不能为空")
						return false;
					}
				}
				this.$refs['dataForm'].validate((valid) => {
					if (valid) {
						this.$http({
							url: this.$http.adornUrl(`/back/goods/${!this.dataForm.id ? 'save' : 'update'}`),
							method: 'post',
							data: this.$http.adornData({
								id: this.dataForm.id || undefined,
								categoryId: this.dataForm.categoryId[this.dataForm.categoryId.length - 1],
								goodsSn: this.dataForm.goodsSn,
								name: this.dataForm.name,
								brandId: this.dataForm.brandId,
								attributeCategory: this.dataForm.attributeCategory,
								goodsNumber: this.dataForm.goodsNumber,
								retailPrice: this.dataForm.retailPrice,
								marketPrice: this.dataForm.marketPrice,
								listPicUrl: this.dataForm.listPicUrl,
								primaryPicUrl: this.dataForm.primaryPicUrl,
								sortOrder: this.dataForm.sortOrder,
								isOnSale: this.dataForm.isOnSale,
								isNew: this.dataForm.isNew,
								isHot: this.dataForm.isHot,
								promotionDesc: this.dataForm.promotionDesc,
								keywords: this.dataForm.keywords,
								goodsBrief: this.dataForm.goodsBrief,
								goodsDesc: this.dataForm.goodsDesc,
								goodsImgList: this.dataForm.goodsImgList,
								attributeEntityList: Object.values(this.dataForm.attributeEntityList)
							})
						}).then(({
							data
						}) => {
							if (data && data.code === 0) {
								for (var i = 0; i < this.uploadImg.length; i++) {
									if (this.dataForm.goodsDesc.indexOf(this.uploadImg[i]) === -1) {
										this.deletePic(this.uploadImg[i])
									}
								}
								for (var k = 0; k < this.goodsDescImgList.length; k++) {
									if (this.dataForm.goodsDesc.indexOf(this.goodsDescImgList[k]) === -1) {
										this.deletePic(this.goodsDescImgList[k])
									}
								}
								this.deletePics(this.oldImg)
								this.$message({
									message: '操作成功',
									type: 'success',
									duration: 1500,
									onClose: () => {
										this.visible = false
										this.$emit('refreshDataList')
										this.$emit('closeDialog')
									}
								})
							} else {
								this.$message.error(data.msg)
							}
						})
					}
				})
			},
			// 上传图片之前的钩子
			beforePicUpload(file) {
				var fileType = ['image/jpeg', 'image/png', 'image/jpg']
				const isPic = fileType.join(',').indexOf(file.type) !== -1
				const isLt2M = file.size / 1024 / 1024 < 2
				if (!isPic) {
					this.$message.error('不支持此格式的图片!')
				}
				if (!isLt2M) {
					this.$message.error('上传图片大小不能超过 2MB!')
				}
				return isPic && isLt2M
			},
			// 主图上传成功时的钩子
			handlePrimaryPicUrlSuccess(response) {
				if (response && response.code === 0) {
					this.dataForm.primaryPicUrl = response.url
					this.newImg.push(response.url)
				} else {
					this.$message.error(response.msg)
				}
			},
			// 列表图片上传成功时的钩子
			handleListPicUrlSuccess(response) {
				if (response && response.code === 0) {
					this.dataForm.listPicUrl = response.url
					this.newImg.push(response.url)
				} else {
					this.$message.error(response.msg)
				}
			},
			// 轮播图上传成功时的钩子
			handleCarouselPicSuccess(response) {
				var that = this
				if (response && response.code === 0) {
					that.newImg.push(response.url)
					if (that.dataForm.id && that.notNewGoodsImg) {
						that.notNewGoodsImg = false
						that.dataForm.goodsImgList = that.oldgoodsImgList
					}
					var carousel = {
						id: '',
						goodsId: '',
						imgUrl: response.url,
						sortOrder: that.dataForm.goodsImgList.length
					}
					that.dataForm.goodsImgList.push(carousel)
				} else {
					that.$message.error(response.msg)
				}
			},
			// 删除按钮点击事件
			deleteBtn(param) {
				var url = this.dataForm[param]
				if (url) {
					this.oldImg.push(url)
					this.dataForm[param] = ''
				}
			},
			// 商品轮播图组件删除方法
			handleRemove(file, fileList) {
				var that = this
				that.dataForm.goodsImgList = []
				if (that.dataForm.id && that.notNewGoodsImg) {
					that.notNewGoodsImg = false
				}
				fileList.forEach(function(value, i) {
					if (value.response.url) {
						var carousel = {
							id: '',
							goodsId: '',
							imgUrl: value.response.url,
							sortOrder: i
						}
						that.dataForm.goodsImgList.push(carousel)
					}
				})
				that.oldImg.push(file.response.url)
			},
			// 属性列表选择事件
			selectAttributeCategory(id) {
				var that = this
				that.attributes = []
				that.dataForm.attributeEntityList = {}
				if (!id) {
					return
				}
				that.$http({
					url: that.$http.adornUrl(`/back/attribute/list`),
					method: 'get',
					params: that.$http.adornParams({
						attributeCategoryId: id
					})
				}).then(({
					data
				}) => {
					if (data && data.code === 0) {
						that.attributes = data.data
						data.data.forEach(function(value, i) {
							var goodsAttribute = {
								id: '',
								goodsId: that.dataForm.id ? that.dataForm.id : '',
								attributeId: value.id,
								value: ''
							}
							that.dataForm.attributeEntityList[value.id] = goodsAttribute
						})
						if (that.goodsAttribute && that.goodsAttribute.length > 0) {
							that.goodsAttribute.forEach(function(item, i) {
								if (that.dataForm.attributeEntityList[item.attributeId]) {
									that.dataForm.attributeEntityList[item.attributeId].value = item.value
								}
							})
						}
					}
				})
			},
			// 查看图片
			handleView(imgUrl) {
				if (!imgUrl) {
					return
				}
				var reg = /(.*)\.(jpg|jpeg|png)$/;
				if (reg.test(imgUrl)) {
					var items = [{
						src: imgUrl
					}];
					var options = {
						index: 0,
						zIndex: 10999
					};
					new PhotoViewer(items, options);
				}
			},
			// 图片查看方法
			handlePictureCardPreview(file) {
				this.handleView(file.url)
			},
			// 删除图片数组
			deletePics(deleteImg) {
				for (var i = 0; i < deleteImg.length; i++) {
					this.deletePic(deleteImg[i])
				}
			},
			// 通过url删除图片
			deletePic(url) {
				this.$http({
					url: this.$http.adornUrl('/sys/oss/deleteByUrl'),
					method: 'post',
					params: this.$http.adornParams({
						'url': url
					})
				})
			},
			// 取消操作
			cancel() {
				var that = this
				that.deletePics(that.newImg)
				that.deletePics(that.uploadImg)
				that.$emit('closeDialog')
				that.visible = false
			},
			// 匹配图片src路径
			matchSrc(str) {
				if (!str) {
					return
				}
				var that = this
				// 匹配图片（g表示匹配所有结果i表示区分大小写）
				var imgReg = /<img.*?(?:>|\/>)/gi
				// 匹配src属性
				var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i
				var arr = str.match(imgReg)
				if (arr) {
					for (var i = 0; i < arr.length; i++) {
						var src = arr[i].match(srcReg)
						// 获取图片地址
						if (src[1]) {
							that.goodsDescImgList.push(src[1])
						}
					}
				}
			}
		}
	}
</script>

<style>
	.area-select.large {
		width: 100%;
	}

	.area-select {
		height: 36px;
	}

	.area-select .area-selected-trigger {
		padding: 0px 15px;
	}

	.userInfo {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.el-form-item.is-error .area-select {
		border-color: #f56c6c;
	}

	.el-form-item.is-success .area-select {
		border-color: #67c23a;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		width: 100px;
		height: 100px;
		line-height: 100px;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		text-align: center;
	}

	.pic-url {
		width: 100%;
		height: 100%;
		display: block;
	}

	.upload-image-cover {
		width: 100%;
		height: 100%;
		position: relative;
	}

	.upload-list-cover {
		position: absolute;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		background: rgba(0, 0, 0, .6);
		color: #ffffff;
		display: flex;
		display: -webkit-flex;
		justify-content: space-around;
		align-items: center;
		font-size: 20px;
	}

	.zzh-img-row {
		margin-bottom: 10px;
	}

	.el-upload--picture-card {
		width: 65px;
		height: 65px;
		line-height: 76px;
	}

	.el-upload-list--picture-card .el-upload-list__item {
		width: 65px;
		height: 65px;
	}
</style>
